<?php
/**
 * Created by PhpStorm.
 * User: chenzhitao
 * Date: 2018/5/9
 * Time: 下午6:29
 */

namespace App\Busi\Traits;


use App\Models\Policy;

Trait PolicyTrait
{
    public function getUserAmountByVoucherId($voucher_id){
        if(!$voucher_id){
            return "";
        }
        $where = [
            ["voucher_id","=",$voucher_id],
            ["flag","=",1]
        ];
        $field = ["id","amount"];
        $data = Policy::where($where)->select($field)->first();
        if($data){
            return $data['amount'];
        }else{
            return "";
        }
    }
    public function getUserAllAmountByUserId($userid){
        if(!$userid){
            return "";
        }
        $where = [
            ["user_id","=",$userid],
            ["flag","=",1]
        ];
        $field = ["id","amount"];
        $data = Policy::where($where)->select($field)->get();

        $amount = 0;
        if($data){
            foreach ($data as $item){
                $amount = $amount + $item['amount'];
            }
        }
        return $amount;
    }
    public function decreaseAmount($userid,$offNum = 1){
        $where = [
            ['user_id','=',$userid]
        ];
        $fields = ["id","amount"];
        $policyList = Policy::where($where)->select($fields)->orderBy('created_at','asc')->get();
        foreach ($policyList as $item){
            if($item['amount'] >0){
                Policy::where('id', $item['id'])->decrement('amount', $offNum);
                break;
            }
        }
        return;

    }
}